﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Transactions;
using System.Web;
using System.Web.Http;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Web.WebPages.OAuth;
using PublishNews.Entities;
using PublishNews.Repositories;
using WebMatrix.WebData;
using PublishNews.Filters;
using PublishNews.Models;
using Microsoft.AspNet.Identity.EntityFramework;
using AutoMapper;

namespace PublishNews.Controllers
{
    [RoutePrefix("api/Account")]
    public class AccountController : ApiController
    {
        private const string LocalLoginProvider = "Local";
        public UserManager<User> UserManager { get; private set; }

        public AccountController(UserManager<User> userManager)
        {
            UserManager = userManager;
        }


        // POST api/Account/Logout
        [Route("Logout")]
        public IHttpActionResult Logout()
        {
            Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);
            return Ok();
        }


        // POST api/Account/Login
        [Route("Login")]
        public async Task<IHttpActionResult> Login(LoginViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var user = await UserManager.FindAsync(model.UserName, model.Password);

            if (user != null)
            {
                return Ok(user.Id);
            }
            else
            {
                return NotFound();

            }
        }


        // POST api/Account/RemoveLogin
        [Route("RemoveLogin")]
        public async Task<IHttpActionResult> RemoveLogin(RemoveLoginBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            IdentityResult result;

            if (model.LoginProvider == LocalLoginProvider)
            {
                result = await UserManager.RemovePasswordAsync(User.Identity.GetUserId());
            }
            else
            {
                result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(),
                    new UserLoginInfo(model.LoginProvider, model.ProviderKey));
            }

            IHttpActionResult errorResult = GetErrorResult(result);

            if (errorResult != null)
            {
                return errorResult;
            }

            return Ok();
        }

        // POST api/Account/Register
        [System.Web.Mvc.AllowAnonymous]
        [Route("Register")]
        public IHttpActionResult Register(RegisterBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            User user = new User
            {
                UserName = model.Email,
                Email = model.Email,
                PhoneNumber = model.PhoneNumber,
                FullName = model.FullName,
                HideEmail = model.HideEmail,
                RejectNews = model.RejectNews,
                IsAdministrator = false
            };

            IdentityResult result = UserManager.Create(user, model.Password);
            IHttpActionResult errorResult = GetErrorResult(result);

            if (errorResult != null)
            {
                return errorResult;
            }

            return Ok(new { id = user.Id });
        }

        [Route("ChangePassword")]
        public IHttpActionResult ChangePassword(ChangePasswordModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            IdentityResult result = UserManager.ChangePassword(model.UserId, model.CurrentPassword, model.NewPassword);
            IHttpActionResult errorResult = GetErrorResult(result);

            if (errorResult != null)
            {
                return Ok(false);
            }
            return Ok(true);
        }

        [Route("UpdateProfile")]
        public IHttpActionResult UpdateProfile(EditUserModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            var oldUser = UserManager.FindById(model.Id);

            oldUser.FullName = model.FullName;
            oldUser.PhoneNumber = model.PhoneNumber;
            oldUser.Fax = model.Fax;
            oldUser.HideEmail = model.HideEmail;
            oldUser.RejectNews = model.RejectNews;

            IdentityResult result = UserManager.Update(oldUser);

            IHttpActionResult errorResult = GetErrorResult(result);

            if (errorResult != null)
            {
                return Ok(false);
            }
            return Ok(true);
        }

        [Route("Get")]
        public IHttpActionResult Get(string userId)
        {
            var user = UserManager.FindById(userId);
            if(user == null)
            {
                return NotFound();
            }
            var model = Mapper.Map<ViewUserModel>(user);
            return Ok(model);
        }


        #region Helpers

        private IAuthenticationManager Authentication
        {
            get { return Request.GetOwinContext().Authentication; }
        }

        private IHttpActionResult GetErrorResult(IdentityResult result)
        {
            if (result == null)
            {
                return InternalServerError();
            }

            if (!result.Succeeded)
            {
                if (result.Errors != null)
                {
                    foreach (string error in result.Errors)
                    {
                        ModelState.AddModelError("", error);
                    }
                }

                if (ModelState.IsValid)
                {
                    // No ModelState errors are available to send, so just return an empty BadRequest.
                    return BadRequest();
                }

                return BadRequest(ModelState);
            }

            return null;
        }

        #endregion
    }
}
